package com.hnkywl.sts.dao.htdygl;

import com.hnkywl.sts.entity.htgl.Htys;
import net.ruixin.orm.hibernate.Page;
import net.ruixin.orm.hibernate.SimpleHibernateTemplate;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.hibernate.tool.hbm2x.StringUtils;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: nianjunyan
 * Date: 13-4-11
 * Time: 上午11:46
 * To change this template use File | Settings | File Templates.
 */
@Repository
public class HtysdyDao extends SimpleHibernateTemplate<Htys, Long> {

    /**
     * 查询合同元素定义
     *
     * @param htdyId
     * @param htysmc
     * @param pageNo
     * @param pageSize @return
     */
    public Page<Htys> findHtdyList(Long htdyId, String htysmc, int pageNo, int pageSize) {

        String hql = null;
        List<Object> param = new ArrayList<Object>();
        StringBuilder condition = new StringBuilder();
        Page<Htys> page = new Page<Htys>(pageNo, pageSize, 0);
        //==============条件拼接===============
        if (null != htdyId && htdyId > 0) {
            if (condition.length() != 0) {
                condition.append(" and ");
            }

            condition.append(" htdy_id = ?");
            param.add(htdyId);
        }

        if (StringUtils.isNotEmpty(htysmc)) {
            if (condition.length() != 0)
                condition.append(" and ");
            condition.append(" mc like ? ");
            param.add("%" + htysmc.trim() + "%");
        }
        //==============记录数量===============
        hql = "select count(*) from Htys";
        if (condition.length() != 0)
            hql = hql + " where " + condition;
        Long count = null;
        if (param.size() != 0) {
            count = (Long) findUnique(hql, param.toArray());
            page.setTotalCount(count.intValue());
        } else {
            count = (Long) findUnique(hql);
            page.setTotalCount(count.intValue());
        }
        if (count == 0)
            return page;
        //==============查询结果===============
        hql = "from Htys ";
        if (condition.length() != 0)
            hql = hql + " where " + condition + "order by htdy.id desc";
        if (param.size() != 0)
            return find(page, hql, param.toArray());
        return find(page, hql);
    }
}
